﻿using AduSkin.Controls.Metro;
using DBMC_Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace DBMC
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool isDragging;
        private Point startPoint;
        public Minecraft minecraft = new Minecraft();
        Danbai danbai = new Danbai();
        public string name, uuid, accessToken, refresh_token, type;
        public int memory;
        public bool StartTopmost, StartTools, GameTips;
        public ObservableCollection<UserInfo> Users { get; set; }
        LauncherCore launcherCore = new LauncherCore();

        private string GetJavaPathFromJson
        {
            get
            {
                string javaPath = string.Empty;

                if (launcherCore.ConfigFileExists)
                {
                    // 读取JSON文件的内容
                    string jsonData = File.ReadAllText(launcherCore.ConfigFile);

                    // 反序列化JSON内容到RootObject类的实例
                    RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);

                    // 获取JavaPath的值
                    if (dbmcData != null)
                    {
                        javaPath = dbmcData.JavaPath;
                    }
                }

                return javaPath;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            LoadUsers();
        }

        public void LoadUsers()
        {
            LauncherCore.WriteLog("启动器核心：主页面 - 窗口打开正常");
            if (launcherCore.ConfigFileExists)
            {
                LauncherCore.WriteLog("启动器核心：主页面 - 查找账号信息");
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);

                if (dbmcData.UseMemory > 0)
                {
                    memory = dbmcData.UseMemory;
                }
                StartTopmost = dbmcData.StartTopmost;
                StartTools = dbmcData.StartTools;
                GameTips = dbmcData.GameTips;
                if (dbmcData?.Account != null)
                {
                    Users = new ObservableCollection<UserInfo>(dbmcData.Account);

                    List<UserInfo> selectedUsers = Users.Where(u => u.IsSelected).ToList();
                    if (selectedUsers.Count <= 0)
                    {
                        LauncherCore.WriteLog("启动器核心：主页面 - 未查到有启用账号信息");
                        UserBtn.Visibility = Visibility.Hidden;
                        UserAddBtn.Visibility = Visibility.Visible;
                        GameStart.IsEnabled = false;
                        return;
                    }
                    else
                    {
                        foreach (UserInfo user in selectedUsers)
                        {
                            LoadHead(user.Name);
                            UserName.Text = user.Name;
                            UserType.Text = user.DisplayType;
                            name = user.Name;
                            uuid = user.UUID;
                            accessToken = user.Access_Token;
                            refresh_token = user.Refresh_Token;
                            type = user.Type;
                        }
                        UserBtn.Visibility = Visibility.Visible;
                        UserAddBtn.Visibility = Visibility.Hidden;
                        GameStart.IsEnabled = true;
                        LauncherCore.WriteLog($"启动器核心：主页面 - 已查到有启用账号信息：{name} - {uuid} - {UserType.Text}");
                    }
                }
            }
        }

        private BitmapImage DecodeImageFromBase64(string base64String)
        {
            BitmapImage image = new BitmapImage();
            if (!string.IsNullOrEmpty(base64String))
            {
                byte[] imageBytes = Convert.FromBase64String(base64String);
                using (MemoryStream memStream = new MemoryStream(imageBytes))
                {
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = memStream;
                    image.EndInit();
                    image.Freeze(); // 因为是在非UI线程使用UI资源，所以进行冻结
                }
            }
            return image;
        }

        private void LoadHead(string name)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 加载用户头像");
            // 文件缓存目录
            string cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"Temp", "DBMC", "MCImageCache");
            string cacheFile = Path.Combine(cacheDir, $"{name}.png");

            // 检查缓存是否存在且有效
            if (File.Exists(cacheFile) && (DateTime.Now - File.GetLastWriteTime(cacheFile)).TotalDays < 1)
            {
                // 从本地缓存加载图像
                BitmapImage image = new BitmapImage(new Uri(cacheFile));
                HeadSkin.Source = image;
                LauncherCore.WriteLog($"启动器核心：主页面 - 已从缓存加载用户头像");
            }
            else
            {
                // 尝试从网络加载图像
                BitmapImage image = new BitmapImage();

                try
                {
                    image.BeginInit();
                    image.UriSource = new Uri("https://mineskin.eu/helm/" + $"{name}" + "/100.png", UriKind.Absolute);
                    image.CacheOption = BitmapCacheOption.OnLoad; // 设置缓存选项
                    image.DownloadCompleted += (s, e) =>
                    {
                        // 图像下载成功，保存到本地缓存
                        SaveImageToCache(image, cacheDir, cacheFile);
                    };
                    image.DownloadFailed += (s, e) =>
                    {
                        // 如果下载失败，使用默认的Base64编码的图像
                        image = DecodeImageFromBase64(Danbai.HandImage);
                        HeadSkin.Source = image;
                    };
                    image.EndInit();
                    HeadSkin.Source = image;
                    LauncherCore.WriteLog($"启动器核心：主页面 - 已从网络加载用户头像");
                }
                catch
                {
                    // 如果在初始化图像期间发生异常，使用Base64默认图像
                    image = DecodeImageFromBase64(Danbai.HandImage);
                    HeadSkin.Source = image;
                }
            }
        }

        // 保存图像到本地缓存
        private void SaveImageToCache(BitmapSource image, string cacheDir, string cacheFile)
        {
            if (!Directory.Exists(cacheDir))
            {
                Directory.CreateDirectory(cacheDir);
            }

            using (var fileStream = new FileStream(cacheFile, FileMode.Create))
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(fileStream);
                LauncherCore.WriteLog($"启动器核心：主页面 - 用户头像已缓存");
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void Grid_Click(object sender, RoutedEventArgs e)
        {
            User user = new User();
            if (user.ShowDialog() == true && user.DialogResult == true)
            {
                LoadUsers();
            }
        }

        private void StartGame_ButtonClick(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 用户点击了“启动游戏”按钮");
            if (!minecraft.IsJava)
            {
                if (!minecraft.CheckJavaVersion)
                {
                    if (GetJavaPathFromJson == "")
                    {
                        LauncherCore.WriteLog($"启动器核心：主页面 - 唤起启动游戏窗口失败，因为未设置Java");
                        AduMessageBox.Show("Java路径未设置",null,MessageBoxButton.OK,MessageBoxImage.Error);
                        return;
                    }
                }
            }
            if (minecraft.IsDanBaiGameReady)
            {
                StartGame(true);
            }
            else
            {
                LauncherCore.WriteLog($"启动器核心：主页面 - 唤起启动游戏窗口失败，因为游戏本体不存在");
                AduMessageBox.Show("游戏不见了QAQ", "启动失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Home_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 打开“主页”");
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
            {
                FileName = "https://dbmc.dbhg.top/",
                UseShellExecute = true
            });
            LauncherCore.WriteLog($"启动器核心：主页面 - 成功打开了“主页”");
        }

        private void OpenTools_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 唤起“工具”窗口");
            Tools tools = new Tools();
            tools.ShowDialog();
        }

        public void StartGame(bool main = false)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 唤起“启动游戏”窗口");
            Hide();
            GameStarting gameStarting = new GameStarting(memory, name, uuid, accessToken, refresh_token, main, type == "msa", StartTools, GameTips);
            gameStarting.Show();
            gameStarting.Topmost = true;
            gameStarting.Topmost = StartTopmost;
        }

        private void Settings_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 唤起“设置”窗口");
            Settings settings = new Settings();
            bool? res = settings.ShowDialog();
            if (res == true)
            {
                LoadUsers();
            }
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：主页面 - 唤起“关于”窗口");
            About about = new About();
            about.ShowDialog();
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Minimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }
    }
}
